package com.yp.infrastructure.mdb.model;

import com.yp.infrastructure.common.model.BaseModel;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.experimental.SuperBuilder;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;

import java.lang.reflect.Constructor;
import java.sql.Timestamp;
import java.util.Date;
import java.util.UUID;

/**
 * 数据表实例基类
 */

@Data
@Slf4j
@EqualsAndHashCode(callSuper = true)
@SuperBuilder(toBuilder = true)
public abstract class BaseEntity extends BaseModel {

    private String id;
    /**
     * 数据逻辑状态
     */
    private int status;

    /**
     * 逻辑删除标记
     */
    private Boolean deleted;

    /**
     * 创建时间
     */
    private Date creationDate;

    /**
     * 更新时间
     */
    private Date updatedDate;


    /**
     * 默认构建器， 初始化标记位值
     */
    public BaseEntity() {
        Date now = new Timestamp(System.currentTimeMillis());
        deleted = false;
        creationDate = now;
        updatedDate = now;
    }

    /**
     * 根据Id创建实例
     *
     * @param id id.
     */
    protected BaseEntity(String id) {
        this.id = id;
    }


    /**
     * 相同属性名的类拷贝
     *
     * @param clazz  目标类
     * @param source 数据源
     * @param <T>    泛型类
     * @param <D>    值实例
     * @return .
     */
    public static <T extends BaseEntity, D extends BaseEntity> T from(Class<T> clazz, D source) {
        if (null == source) return null;
        try {
            T target = BaseModel.newInstance(clazz);
            if (null == target) return null;
            BeanUtils.copyProperties(source, target);
            if (StringUtils.isEmpty(source.getId())) {
                target.setId(UUID.randomUUID().toString());
            }
            return target;
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
        return null;
    }
}
